package com.eternal.notification.ui;

import androidx.lifecycle.Observer;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;

import com.afollestad.materialdialogs.MaterialDialog;
import com.eternal.base.data.RepositoryInjection;
import com.eternal.base.database.entity.Notification;
import com.eternal.base.global.ActivityEvent;
import com.eternal.base.global.BluetoothKey;
import com.eternal.framework.binding.command.BindingAction;
import com.eternal.framework.bus.Messenger;
import com.eternal.framework.component.BaseFragment;
import com.eternal.framework.utils.GsonUtils;
import com.eternal.framework.utils.Utils;
import com.eternal.notification.BR;
import com.eternal.notification.R;
import com.eternal.notification.databinding.FragmentOtherBinding;
import com.eternal.notification.model.OtherModel;
import com.eternal.widget.guqiang.IEffectBar;

/**
 * Created by Administrator
 * On 2020/5/11
 * Description:
 * @author Administrator
 */
public class OtherFragment extends BaseFragment<FragmentOtherBinding, OtherModel> {
    private String ok;
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_other;
    }

    @Override
    public int initVariableId() {
        return BR.otherModel;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle arguments=getArguments();
        boolean isDegree=arguments.getBoolean(ActivityEvent.DEVICE_DEGREE);
        String temp=arguments.getString(ActivityEvent.NOTIFICATION);
        byte type=arguments.getByte(ActivityEvent.NOTIFICATION_TYPE);
        initView(isDegree, temp!=null, type);
        registerMessage();
        bindEvent();
        viewModel.init(RepositoryInjection.providerNotificationRepository(),
                arguments.getString(ActivityEvent.DEVICE_MAC),
                arguments.getByte(ActivityEvent.DEVICE_PORT),
                GsonUtils.fromJson(temp, Notification.class), isDegree, type);
    }

    @Override
    public void onDestroyView() {
        unregisterMessage();
        super.onDestroyView();
    }

    private void initTmpAndHum(){
        binding.calTmp.setListener(new AbstractAdapter() {
            @Override
            public void onEndFirst(boolean isProgress,int value) {
                viewModel.hTmp.setValue((char) value);
            }

            @Override
            public void onEndLast(boolean isProgress,int value) {
                viewModel.lTmp.setValue((char) value);
            }

            @Override
            public void onFirstChecked(boolean b) {
                viewModel.hTmpSwitch.setValue(b);
            }

            @Override
            public void onLastChecked(boolean b) {
                viewModel.lTmpSwitch.setValue(b);
            }
        });
        binding.calHum.setListener(new AbstractAdapter() {
            @Override
            public void onEndFirst(boolean isProgress,int value) {
                viewModel.hHum.setValue((byte) value);
            }

            @Override
            public void onEndLast(boolean isProgress,int value) {
                viewModel.lHum.setValue((byte) value);
            }

            @Override
            public void onFirstChecked(boolean b) {
                viewModel.hHumSwitch.setValue(b);
            }

            @Override
            public void onLastChecked(boolean b) {
                viewModel.lHumSwitch.setValue(b);
            }
        });
    }

    private void initView(boolean isDegree, boolean isEdit, byte type){
        initTmpAndHum();
        IEffectBar.Factory factory=new IEffectBar.Factory() {
            @Override
            public String getText(int value) {
                return Utils.getString(R.string.tip_percent_num, value);
            }
        };
        binding.calHum.setFactory(factory);
        factory=new IEffectBar.Factory() {
            @Override
            public String getText(int value) {
                if(viewModel.isDegree){
                    return Utils.getString(R.string.tip_degree_num, value);
                }else{
                    return Utils.getString(R.string.tip_fah_num, value);
                }
            }
        };
        binding.calTmp.setFactory(factory);
        if(isDegree){
            String min="0℃",max="90℃";
            binding.cpHighTmp.setValue(min,max,0, 90);
            binding.cpLowTmp.setValue(min,max,0, 90);
        }else{
            String min="32℉", max="194℉";
            binding.cpHighTmp.setValue(min,max,32, 162);
            binding.cpLowTmp.setValue(min,max,32, 162);
        }
        if(isEdit){
            binding.btnDelete.setVisibility(View.VISIBLE);
        }
        initInfo(type, isEdit);
    }

    private void initInfo(byte type, boolean isEdit){
        if(type== BluetoothKey.NOTIFICATIONS){
            binding.tsvTmpHum.setInfo(Utils.getString(R.string.notify_info_temp_hum));
            binding.tsvTimeOn.setInfo(Utils.getString(R.string.notify_info_time_on));
            binding.tsvTimeOff.setInfo(Utils.getString(R.string.notify_info_time_off));
            binding.tsvAuto.setInfo(Utils.getString(R.string.notify_info_auto));
            binding.tsvSchedule.setInfo(Utils.getString(R.string.notify_info_schedule));
            binding.tsvCycle.setInfo(Utils.getString(R.string.notify_info_cycle));
            binding.ivHead.setImageResource(R.mipmap.group_notification);
            binding.tvNotificationDes.setVisibility(View.VISIBLE);
            if(!isEdit){
                viewModel.name.setValue(Utils.getString(R.string.notify_default_name));
            }
        }else if(!isEdit){
            viewModel.name.setValue(Utils.getString(R.string.alarm_default_name));
        }
    }

    private void bindEvent(){
        bindTmpAndHum();
        ok=Utils.getString(R.string.tip_ok);
        viewModel.tmpHum.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                if(aBoolean==Boolean.TRUE){
                    binding.elTmpHum.expand();
                }else{
                    binding.elTmpHum.collapse();
                }
            }
        });
        viewModel.nameEdit.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if(ok.equals(s)){
                    binding.etEditName.setEnabled(true);
                    binding.etEditName.setFocusable(true);
                    binding.etEditName.setFocusableInTouchMode(true);
                    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        binding.etEditName.requestFocus();
                        imm.showSoftInput(binding.etEditName, 0);
                        binding.etEditName.setSelection(binding.etEditName.getText().length());
                    }
                }else{
                    binding.etEditName.clearFocus();
                    binding.etEditName.setEnabled(false);
                    binding.etEditName.setFocusable(false);
                    binding.etEditName.setFocusableInTouchMode(false);
                }
            }
        });
    }

    private void bindTmpAndHum(){
        viewModel.hTmp.observe(this, new Observer<Character>() {
            @Override
            public void onChanged(@Nullable Character character) {
                if(binding.cpHighTmp.getProgress()!=character){
                    binding.cpHighTmp.setProgress(character);
                }
            }
        });
        viewModel.lTmp.observe(this, new Observer<Character>() {
            @Override
            public void onChanged(@Nullable Character character) {
                if(binding.cpLowTmp.getProgress()!=character){
                    binding.cpLowTmp.setProgress(character);
                }
            }
        });
        viewModel.hHum.observe(this, new Observer<Byte>() {
            @Override
            public void onChanged(@Nullable Byte param) {
                if(binding.cpHighHum.getProgress()!=param){
                    binding.cpHighHum.setProgress(param);
                }
            }
        });
        viewModel.lHum.observe(this, new Observer<Byte>() {
            @Override
            public void onChanged(@Nullable Byte param) {
                if(binding.cpLowHum.getProgress()!=param){
                    binding.cpLowHum.setProgress(param);
                }
            }
        });
        viewModel.hTmpSwitch.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean param) {
                if(binding.cpHighTmp.isChecked()!=param){
                    binding.cpHighTmp.setChecked(param);
                }
            }
        });
        viewModel.lTmpSwitch.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean param) {
                if(binding.cpLowTmp.isChecked()!=param){
                    binding.cpLowTmp.setChecked(param);
                }
            }
        });
        viewModel.hHumSwitch.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean param) {
                if(binding.cpHighHum.isChecked()!=param){
                    binding.cpHighHum.setChecked(param);
                }
            }
        });
        viewModel.lHumSwitch.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean param) {
                if(binding.cpLowHum.isChecked()!=param){
                    binding.cpLowHum.setChecked(param);
                }
            }
        });
    }

    private void registerMessage(){
        Messenger.getDefault().register(this, NotificationActivity.SHOW_DELETE_DIALOG, new BindingAction() {
            @Override
            public void call() {
                showDelete();
            }
        });
    }

    private void unregisterMessage(){
        Messenger.getDefault().unregister(this);
    }

    private void showDelete(){
        View view=LayoutInflater.from(getContext()).inflate(com.eternal.res.R.layout.reconfirm_dialog, null, false);
        final MaterialDialog dialog=new MaterialDialog.Builder(getContext())
                .backgroundColor(0x00ffffff)
                .customView(view, false)
                .build();
        view.findViewById(com.eternal.res.R.id.tv_cancel)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
        view=dialog.getCustomView();
        view.findViewById(com.eternal.res.R.id.tv_confirm)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewModel.delete();
                        dialog.dismiss();
                    }
                });
        dialog.show();
    }
}
